package com.example.file.security.utils;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.file.security.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {

    /**
     * 盐值
     */
    private static final String SING = "AMDXGbO7gGwf3hoFPpm6GwQvFrqoCsn2";


    public static void main(String[] args) {
        Map<String, String> map=Map.of("name","66");
        String token = getToken(map);
        System.out.println(token);

        DecodedJWT tokenInfo = getTokenInfo("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiNjYiLCJleHAiOjE3NDMwNTUyMDJ9.SXACGYJCy4s5VAfRCH2P_787YspXGPVjidE2CcnHOGw");
        System.out.println();
    }

    //生成令牌
    public static String getToken(Map<String, String> map) {
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        //默认7天过期
        calendar.add(Calendar.DATE, 7);
        //新建一个JWT的Builder对象
        JWTCreator.Builder builder = JWT.create();
        //将map集合中的数据设置进payload
        map.forEach(builder::withClaim);
        //设置过期时间和签名
        return builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SING));
    }

    /**
     * 验签并返回DecodedJWT
     *
     * @param token 令牌
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    public static User getUserInfo(String token) {

        if (StringUtils.isBlank(token)) {
            return null;
        }

        DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
        if (tokenInfo == null || CollectionUtils.isEmpty(tokenInfo.getClaims())) {
            return null;
        }

        Map<String, Claim> claims = tokenInfo.getClaims();
        return JSONObject.parseObject(JSONObject.toJSONString(claims), User.class);

    }
}
